package org.example.controller;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.example.domain.SysUser;
import org.example.vo.SysUserVo;
import org.example.service.SysUserService;
import org.example.util.Result;
import org.spring.kun.common.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Api(tags = {"用户接口"})
@RestController
@RequestMapping("sysUser")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private HttpServletResponse response;


    /**
     * 登录和swagger接口测试
     * @param sysUser
     * @return
     */
    @ApiOperation(value = "登录测试接口")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 600,message = "失败")
    })
    @RequestMapping("login")
    public Result login(@RequestBody SysUser sysUser){
        Object o = redisTemplate.opsForValue().get(sysUser.getUid());
        if(!o.equals(sysUser.getCode())){
            return Result.fail("验证码错误");
        }
        SysUser user = sysUserService.getOne(sysUser.getUserName());
        if (user==null){
            return Result.fail("账号错误");
        }else if(!user.getPassword().equals(DigestUtil.md5Hex(sysUser.getPassword()+"2110a"))){
            return Result.fail("密码错误");
        }
        String token = JWT.create()
                .setPayload("username", user.getUserName())
                .setSigner(JWTSignerUtil.none())
                .sign();
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("username",user.getUserName());
        return Result.success(map);
    }

    /**
     * 控制台查看密码
     */
    @PostConstruct
    public void pwd(){
        System.err.println(DigestUtil.md5Hex("123"+"2110a"));
    }

    /**
     * 生成验证码
     * @param uid
     * @throws IOException
     */
    @RequestMapping("getCode")
    public void getCode(String uid) throws IOException {
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        captcha.write(response.getOutputStream());
        redisTemplate.opsForValue().set(uid,captcha.getCode(),1, TimeUnit.MINUTES);
    }
    /**
     * 用户管理
     */
    @ApiOperation(value = "查询测试接口")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 600,message = "失败")
    })
    @RequestMapping("list")
    public Result list(@RequestBody SysUserVo sysUserVo, Integer current, Integer size){
        PageHelper.startPage(current,size);
        List<SysUser> list = sysUserService.list(sysUserVo);
        return Result.success(new PageInfo<>(list));
    }

    /**
     * 添加用户和角色
     */
    @ApiOperation(value = "添加测试接口")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 600,message = "失败")
    })
    @RequestMapping("saveUser")
    public Result saveUser(@Valid @RequestBody SysUser sysUser,BindingResult result){
        if(result.hasErrors()){
            return Result.fail(result.getAllErrors().get(0).getDefaultMessage());
        }
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(JSONUtil.toJsonStr(sysUser), 1, 1, TimeUnit.MINUTES);
        if(!aBoolean){
            return Result.fail("表单重复提交");
        }
        boolean b = sysUserService.saveUser(sysUser);
        return b?Result.success():Result.fail();
    }
    /**
     * 修改用户和角色
     */
    @ApiOperation(value = "回显测试接口")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 600,message = "失败")
    })
    @RequestMapping("selectUserById")
    public Result selectUserById(Long userId){
        SysUser sysUser = sysUserService.selectUserById(userId);
        return Result.success(sysUser);
    }
    @ApiOperation(value = "修改测试接口")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 600,message = "失败")
    })
    @RequestMapping("updateUser")
    public Result updateUser(@RequestBody SysUser sysUser){
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(JSONUtil.toJsonStr(sysUser), 1, 1, TimeUnit.MINUTES);
        if(!aBoolean){
            return Result.fail("表单重复提交");
        }
        boolean b = sysUserService.updateUser(sysUser);
        return b?Result.success():Result.fail();
    }
    @ApiOperation(value = "角色回显测试接口")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 600,message = "失败")
    })
    @RequestMapping("rolesById")
    public Result rolesById(Long userId){
        List<Long> roleId = sysUserService.rolesById(userId);
        return Result.success(roleId);
    }
    @RequestMapping("postById")
    public Result postById(Long userId){
        List<Long> postId = sysUserService.postById(userId);
        return Result.success(postId);
    }
    /**
     * 批量删除
     */
    @ApiOperation(value = "批量删除测试接口")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 600,message = "失败")
    })
    @RequestMapping("delAll")
    public Result delAll(Long[] userId){
        System.err.println(JSONUtil.toJsonStr(userId));
//        boolean b = sysUserService.delAll(Arrays.asList(userId));
        boolean b = sysUserService.updateUsers(Arrays.asList(userId));
        return b?Result.success():Result.fail();
    }
    /**
     * 导出
     */
    @ApiOperation(value = "导出测试接口")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 600,message = "失败")
    })
    @RequestMapping("excelOut")
    public void excelOut(){
        List<SysUser> list = sysUserService.listExcel();
        ExcelUtils.exportExcel(list,"用户表格导出","这是sheet1",response);
    }
}
